﻿#region references
using System;
using System.Web;
using System.Configuration;
using System.Web.SessionState;
using System.IO;
using System.Threading;
using System.Security.Principal;

/* Project dependencies */
using IcaGames.Logging;
using IcaGames.Database.ObjectManagement;
#endregion

public class DownloadHandler : IHttpHandler, IReadOnlySessionState, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
    {
        if (context.User.Identity.IsAuthenticated)
        {
            try
            {
                /* Get the QueryString with the selected game and userId from the previous page */
                string[] param = context.Request.QueryString["g"].Split('_');
                int userId = int.Parse(context.Request.QueryString["u"]);
                int cartId = int.Parse(context.Request.QueryString["o"]);

                /* Get the userId from the download sesssion*/
                int sessId = (int)context.Session["download"];

                if (sessId == userId)
                {
                    if (CheckDownloadAvailable(cartId, int.Parse(param[0]), param[1]))
                    {
                        string path = context.Server.MapPath("~/upload") + "\\" + param[0] + "\\" + param[0] + ".rar";

                        /* Create FileInfo and send the file to the user */
                        FileInfo fi = new FileInfo(path);
                        context.Response.ContentType = "application/x-rar-compressed";
                        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
                        context.Response.AddHeader("Content-Length", fi.Length.ToString());
                        context.Response.WriteFile(fi.FullName);

                        /* Update the database that the file has been downloaded */
                        UpdateDatabase(cartId, int.Parse(param[0]), param[1]);
                    }
                    else { ShowErrorMessage(context, "U bent niet gemachtigd deze game te downloaden."); }
                }
                else { ShowErrorMessage(context, "U bent niet gemachtigd deze game te downloaden."); }
            }
            catch (Exception ex)
            {
                Log.CreateLog("Exception while requesting download QueryString", "DOWNLOADHANDLER");
                Log.CreateLog(ex.Message, "DOWNLOADHANDLER");
            }
        }
        else { ShowErrorMessage(context, "U bent niet gemachtigd deze game te downloaden."); }
    }

    /*
     * Function to show an error message depening on an occured error.
     * 
     * @param
     * context: The HttpContext for the current request.
     * message: The message that has to be shown to the user.
     */ 
    private void ShowErrorMessage(HttpContext context, string message)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write(message);
    }

    /*
     * Function that updates the database when the file has been downloaded.
     * 
     * @param
     * cartId: The id of the shopping cart of the game.
     * gameNr: The id of the game that has been downloaded.
     * platform: The platform for which the download has been completed.
     */ 
    private void UpdateDatabase(int cartId, int gameNr, string platform)
    {
        CartManagement.UpdateUserDownloads(cartId, gameNr, platform);
    }

    /*
     * Function to check if the user has downloads available for the selected game.
     * 
     * @param
     * cartId: The id of the shopping cart of the game.
     * gameNr: The id of the game that has been downloaded.
     * platform: The platform for which the download has been completed.
     * 
     * @returns
     * True if the user has downloads available.
     * False if the user doesn't have downloads available.
     */
    private bool CheckDownloadAvailable(int cartId, int gameNr, string platform)
    {
        return CartManagement.CheckDownloadAvailable(cartId, gameNr, platform);
    }
}
